import React, { useEffect, useState } from 'react';
import { Row } from 'antd';
import classNames from 'classnames';
import { RowProps as AntdRowProps } from 'antd/lib/row';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';
import styles from './row.module.scss';

const pd = { padding: '10px' };

const ControlMap = {
  'table': (props: any) => (
    <table
      border={0}
      cellSpacing={0}
      cellPadding={2}
      {...props}
      className={styles.table} />
  ),
  'table-header-group': (props: any) => <thead {...props} />,
  'table-row-group': (props: any) => <tbody {...props} className='' />,
  'table-row': (props: any) => <tr {...props} className={styles.collapse} />
};

export interface RowProps extends CanvasItemProps {
  rowProps: AntdRowProps & {
    tableStyle?: string;
    rowStyle?: string;
    pageBreakAfter?: boolean; // 是否在元素后插入分页符
    printOnEveryPage?: boolean; // 是否在每一页的表格上面打印
  };
}

export default (props: RowProps) => {
  const { isDesign, domComplete, rowProps, ...canvasProps } = props;
  const [height, setHeight] = useState<null | string>(null);
  const [top, setTop] = useState<null | string>(null);

  useQueryControlWrap(canvasProps.id, '', domComplete);

  useEffect(() => {
    if (props._id && !props.isDesign) {
      const tr = document.querySelector('#' + props._id!);

      if (tr) {
        const parentNode = tr.parentNode as HTMLDivElement;

        if (parentNode && parentNode.tagName.toUpperCase() === 'TD') {
          const parentchildren = Number(parentNode.dataset.parentchildren);

          const trChild = document.querySelectorAll(`#${parentNode.id} > tr`);

          if (trChild.length) {
            let curIndex = 0;

            trChild.forEach((item: any, index: number) => {
              if (item.id === props._id) {
                curIndex = index;
              }
            });

            setTop(100 / parentchildren * curIndex + '%');
          }

          if (parentchildren) {
            setHeight(100 / parentchildren + '%');
          }
        }
      }
    }
  }, [props._id, props.isDesign]);

  let style: React.CSSProperties = isDesign ? pd : {};

  let Component: any = Row;

  if (rowProps?.tableStyle && !isDesign) {
    Component = ControlMap[rowProps.tableStyle];
  }

  if (height) style.height = height;
  if (top) style.top = top;

  if (isDesign) style.minHeight = '60px';

  if (rowProps?.rowStyle) {
    try {
      style = {
        zIndex: 9,
        ...style,
        ...JSON.parse(rowProps?.rowStyle)
      };
    } catch (error) { }
  }

  return (
    <Component
      id={props._id}
      {...rowProps}
      {...canvasProps}
      className={classNames(styles.row, {
        [styles.rowView]: !isDesign
      })}
      style={style}>
    </Component>
  );
};